/*
================================================================================
EVENTSTUDY PROGRAM USAGE INSTRUCTIONS
================================================================================

SYNTAX: eventstudy plotname keep_frame beta_coef se_coef pvalue yaxis_option [ymin] [yinterval] [ymax]

REQUIRED ARGUMENTS:
1. plotname     - String identifier for the plot (creates frame "coefplot[plotname]")
2. keep_frame   - Binary (0/1): 
                  0 = drop frame after plotting (recommended for most uses)
                  1 = keep frame for further analysis
3. beta_coef    - Main coefficient estimate (from ddtquartile1 or similar)
4. se_coef      - Standard error of main coefficient
5. pvalue       - P-value for significance stars (* p≤0.1, ** p≤0.05, *** p≤0.01)
6. yaxis_option - Y-axis scaling option:
                  "o" = custom range (requires ymin, yinterval, ymax)
                  [blank] = automatic symmetric range based on confidence intervals

OPTIONAL ARGUMENTS (required only if yaxis_option = "o"):
7. ymin         - Custom y-axis minimum
8. yinterval    - Custom y-axis interval for labels
9. ymax         - Custom y-axis maximum

PREREQUISITES:
- Must run regression with alpha_* coefficients first (alpha4-alpha29 expected)
- Program extracts coefficients alpha12-alpha29 (event years -11 to +6)
- Uses results from most recent regression in memory

EXAMPLE USAGE:
reghdfe outcome alpha_* controls, absorb(fe) vce(cluster id)
eventstudy myplot 0 "0.025" "0.012" 0.04 o -.03 .03 .06

This creates an event study plot with:
- Plot saved as frame "coefplotmyplot" 
- Frame dropped after plotting
- Subtitle showing "Top-Quartile × Post = 0.025** [0.012]"
- Custom y-axis from -.03 to .06 with .03 intervals
================================================================================
*/
cap program drop eventstudy
program de eventstudy
cap frame drop coefplot`1'
frame create coefplot`1'
frame coefplot`1': set obs 18
frame coefplot`1': gen estimate = .
frame coefplot`1': gen se = .
frame coefplot`1': gen eyear = -12 + _n
forval i = 12/29 {
loc j = `i'-11
loc b`i' = _b[alpha_`i']
loc se_`i' = _se[alpha_`i']
frame coefplot`1': replace estimate = `b`i'' in `j'
frame coefplot`1': replace se = `se_`i'' in `j'

}
frame coefplot`1': gen ci95hi = estimate + 1.96 * se
frame coefplot`1': gen ci95lo = estimate - 1.96 * se 
frame coefplot`1': gen ci90hi = estimate + 1.64 * se 
frame coefplot`1': gen ci90lo = estimate - 1.64 * se


frame coefplot`1': qui summarize ci95lo
local min_lo = r(min)
frame coefplot`1': qui summarize ci95hi
local max_hi = r(max)
local ymax = max(abs(`min_lo'), abs(`max_hi'))

* After getting the max absolute value (ymax)
frame coefplot`1': local base = 10
* For small values, use a different base
if `ymax' < 2 {
    frame coefplot`1': local base = 1
} 
else if `ymax' < 10 {
    frame coefplot`1': local base = 5
}

* Round up to the nearest multiple of base
frame coefplot`1': local ymax_rounded = ceil(`ymax'/`base')*`base'

* Determine appropriate intervals based on the range size
if `ymax_rounded' > 100 {
    frame coefplot`1': local yinterval = 50
}
else if `ymax_rounded' > 50 {
    frame coefplot`1': local yinterval = 25
}
else if `ymax_rounded' > 20 {
    frame coefplot`1': local yinterval = 10
}
else if `ymax_rounded' > 10 {
    frame coefplot`1': local yinterval = 5
}
else if `ymax_rounded' > 5 {
    frame coefplot`1': local yinterval = 2
}
else {
    frame coefplot`1': local yinterval = 1
}

loc stars ""
if `5' <= .1 {
loc stars "*"
}
if `5' <= .05 {
loc stars "**"
}
if `5' <= .01 {
loc stars "***"
}


*o for optional, if you wish to set a range.
if "`6'" == "o"  {

loc yrange r(`7' `9')
loc ylabel ylabel(`7'(`8')`9')

}

else {
    * Default to automatic symmetric range
    loc yrange r(-`ymax_rounded' `ymax_rounded')
    loc ylabel ylabel(-`ymax_rounded'(`yinterval')`ymax_rounded')
}


frame coefplot`1': twoway (rspike ci95lo ci95hi eyear ,  lc(black)) (scatter estimate eyear , mc(black) m(o)), graphregion(color(white) lcolor(white) lwidth(vthick)) ylab(, nogrid) title("", size(medsmall) color(black)) subtitle("Top-Quartile × Post = `3'`stars' [`4']", size(medsmall) color(black))  ytitle("Coefficient Estimate") ysc(titleg(2) `yrange') `ylabel' yline(0, lc(gs6) lp(dash)) xline(-1, lc(black)) xtitle("Year Relative to Fracking's Introduction") ysc(titleg(2)) legend(off)


if `2' == 0 {
	frame drop coefplot`1'
}
end


